package com.jic.member.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.manager.api.rest.SysUserApi;
import com.jic.member.api.rest.TLabelApi;
import com.jic.member.request.TripUserGroupRequest;
import com.jic.enums.RedisKey;
import com.jic.enums.RedisTime;
import com.jic.member.common.util.BeanUtil;
import com.jic.member.entity.*;
import com.jic.member.entity.power.MememberTypeGrade;
import com.jic.member.enums.ObtainMode;
import com.jic.member.mapper.MememberLabelMapper;
import com.jic.member.mapper.MememberUserMapper;
import com.jic.member.mapper.power.MememberTypeGradeMapper;
import com.jic.member.request.*;
import com.jic.member.response.DistributorShareResponse;
import com.jic.member.response.MemberInfoResponse;
import com.jic.member.response.MememberUserForMarketResponse;
import com.jic.member.response.MememberUserResponse;
import com.jic.member.service.*;
import com.jic.order.api.ToScoreOrderApi;
import com.jic.order.request.ScoreOrderRequest;
import com.jic.point.api.UserPointApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员信息表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-04-16 11:20:10
 */
@Slf4j
@Service
@Component
public class MememberUserServiceImpl implements MememberUserService {

    @Resource
    private MememberUserMapper mememberUserMapper;
    @Resource
    private MememberLabelMapper mememberLabelMapper;

    @Resource
    private TLabelApi tLabelApi;

//    @Resource
//    private UserPointApi userPointApi;

    @Resource
    private SysUserApi sysUserApi;
    @Resource
    private MememberTypeGradeMapper memberTypeGradeMap;

    @Resource
    private MememberActionNewService mememberActionNewService;

    @Resource
    private MememberGrowthObtainService mememberGrowthObtainService;

    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Autowired
    private DisCommissionInfoService disCommissionInfoService;
    @Autowired
    protected DisCashLogService disCashLogService;

    @Resource
    private ToScoreOrderApi toScoreOrderApi;


    /**
     * 新增会员信息
     *
     * @param mememberUser
     * @return
     */
    @Override
    public long insert(MememberUser mememberUser) {
        log.info("开始新增会员信息接口入参,{}", mememberUser);

        if (mememberUser.getId() != null) {
            long flag = mememberUserMapper.update(mememberUser);
            log.info("新增会员信息结束==>结果,{}", flag);
            return flag;
        } else {
            long flag = mememberUserMapper.insert(mememberUser);
            log.info("新增会员信息结束==>结果,{}", flag);
            return flag;
        }
    }

    @Override
    public long delete(Long id) {
        return mememberUserMapper.delete(id);
    }

    @Override
    public long update(MememberUser mememberUser) {
        mememberUser.setUpdateTime(new Date());
        long flag = mememberUserMapper.update(mememberUser);
        return flag;
    }

    /**
     * 修改会员信息
     *
     * @param mememberUser
     * @return
     */
    @Override
    public long updateMemberUserInfo(MememberUser mememberUser) {
        log.info("开始修改会员信息接口入参,{}", mememberUser);
        //通过UUID调用海尔UUC部门查询详情接口获取数据，判断mem_member_user表中是否有数据，有则更新，无则新增（修改按理来说应有数据）
        //TODO:2020/06/16 调用海尔UUC接口获取会员详情
        //mememberUser1为通过UUID调用海尔UUC部门查询详情接口获取到的数据
        MememberUser mememberUserUuc = new MememberUser();
        log.info("通过UUID调用海尔UUC部门查询详情接口返回的会员详情,{}", mememberUserUuc);
        Long uucId = mememberUserUuc.getId();
        log.info("海尔UUC查询详情接口返回的会员详情的ID，{}", uucId);
        log.info("修改会员信息前判断mem_member_user表中是否已有数据，入参,{}", uucId);
        MememberUser mememberUser1 = mememberUserMapper.queryByPrimaryKey(uucId);
        log.info("修改会员信息前判断mem_member_user表中是否已有数据，结果,{}", mememberUser1);
        if (mememberUser1 != null) {
            log.info("查询到mem_memember_user表中已有该数据，则进行数据更新，入参,{}", mememberUserUuc);
            long flag = mememberUserMapper.update(mememberUserUuc);
            log.info("修改会员信息结束==>结果,{}", flag);
            return flag;
        } else {
            log.info("查询到mem_memember_user表中没有该数据，则进行数据新增，入参,{}", mememberUserUuc);
            long flag = mememberUserMapper.insert(mememberUserUuc);
            log.info("修改会员信息结束==>结果,{}", flag);
            return flag;
        }
    }

    /**
     * 查询会员基本信息
     *
     * @param id
     * @return
     */
    @Override
    public MememberUser queryByPrimaryKey(Long id) {
        log.info("开始查询会员信息接口入参,{}", id);
        return mememberUserMapper.queryByPrimaryKey(id);
    }

    /**
     * 定时更新会员信息
     *
     * @param mememberUser
     * @return
     */
    @Override
    public long batchUpdateMemberUser(MememberUser mememberUser) {
        //根据UUID批量定时更新会员信息
        String[] arr = new String[3];
        log.info("需要定时批量更新会员信息的UUID数组arr,{}", arr);
        //需要定时批量更新会员信息的UUID数组arr
        long flag = 1;
        for (int i = 0; i < arr.length; i++) {
            //通过UUID调用海尔UUC部门查询详情接口获取数据，判断mem_member_user表中是否有数据，有则更新，无则新增（修改按理来说应有数据）
            //TODO:2020/06/16 调用海尔UUC接口获取会员详情
            //mememberUser1为通过UUID调用海尔UUC部门查询详情接口获取到的数据
            MememberUser mememberUserUuc = new MememberUser();
            log.info("通过UUID调用海尔UUC部门查询详情接口返回的会员详情,{}", mememberUserUuc);
            Long uucId = mememberUserUuc.getId();
            log.info("海尔UUC查询详情接口返回的会员详情的ID，{}", uucId);
            log.info("更新会员信息前判断mem_member_user表中是否已有数据，入参,{}", uucId);
            MememberUser mememberUser1 = mememberUserMapper.queryByPrimaryKey(uucId);
            log.info("更新会员信息前判断mem_member_user表中是否已有数据，结果,{}", mememberUser1);
            if (mememberUser1 != null) {
                log.info("查询到mem_memember_user表中已有该数据，则进行数据更新，入参,{}", mememberUserUuc);
                flag = mememberUserMapper.update(mememberUserUuc);
                log.info("总共更新数据条数,{}", arr.length, "第,{}", i, "条会员信息更新结束==>结果,{}", flag);
            } else {
                log.info("查询到mem_memember_user表中没有该数据，则进行数据新增，入参,{}", mememberUserUuc);
                flag = mememberUserMapper.insert(mememberUserUuc);
                log.info("总共更新数据条数,{}", arr.length, "第,{}", i, "条会员信息更新结束==>结果,{}", flag);
            }
        }
        return flag;
    }

    @Override
    public List<MememberUser> query(MememberUser mememberUser) {
        return mememberUserMapper.query(mememberUser);
    }


    /**
     * 查询会员列表
     * 需要注意的是【mem_member_user】表中的dept_id是无效的；所以关联的【mem_member_action】表来锁定平台Id；
     *
     * @param mememberUser 请求入参
     * @return 返回封装的实体来
     * @author tzc
     * @date 2020-7-10 19:31:51
     */
    @Override
    public List<MememberUser> listMemberUserInfoInDeptIds(MememberUser mememberUser) {
        return mememberUserMapper.listMemberUserInfoInDeptIds(mememberUser);
    }


    @Override
    public PageResult<MememberUser> queryPage(MememberUser mememberUser, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();

        List<MememberUser> list = mememberUserMapper.queryPage(startIndex, pageQuery.getLimit(), mememberUser);
        long count = mememberUserMapper.queryPageCount(mememberUser);
        AdminOperate adminOperate = mememberUser.getAdminOperate();
        MememberLabel mememberLabel = new MememberLabel();

        list.forEach(itmes -> {
            //查询关联表
            mememberLabel.setDeptId(adminOperate.getDeptId());
            mememberLabel.setMemberId(itmes.getId());
            mememberLabel.setDeleteFlag(0);
            //标签名称
            List<String> labelList = new ArrayList<>();
            List<String> loginList = new ArrayList<>();
            List<MememberLabel> result = mememberLabelMapper.query(mememberLabel);
            if (CollectionUtils.isNotEmpty(result)) {
                result.forEach(label -> {
                    if (null != label.getLabelName()) {
                        labelList.add(label.getLabelName());
                    }
                });
                itmes.setLabelList(labelList);
            }

            itmes.setLoginList(loginList);
        });

        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

//    @Override
//    public PageResult<MememberUser> queryPages(MememberUser mememberUser, Page pageQuery) {
//        //计算下标
//        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
//
//        List<MememberUser> list = mememberUserMapper.queryPage(startIndex, pageQuery.getLimit(), mememberUser);
//        long count = mememberUserMapper.queryPageCount(mememberUser);
//        AdminOperate adminOperate = mememberUser.getAdminOperate();
//        MememberLabel mememberLabel = new MememberLabel();
//
//        list.forEach(itmes -> {
//            //查询关联表
//            mememberLabel.setDeptId(adminOperate.getDeptId());
//            mememberLabel.setMemberId(itmes.getId());
//            mememberLabel.setDeleteFlag(0);
//            BigDecimal point = userPointApi.queryUserPointById(itmes.getId());
//            if (point!=null&&point.compareTo(BigDecimal.ZERO)==1) {
//                itmes.setIntegral(point);
//            }
//            //标签名称
//            List<String> labelList = new ArrayList<>();
//            List<String> loginList = new ArrayList<>();
//            List<MememberLabel> result = mememberLabelMapper.query(mememberLabel);
//            if (CollectionUtils.isNotEmpty(result)) {
//                result.forEach(label -> {
//                    if (null != label.getLabelName()) {
//                        labelList.add(label.getLabelName());
//                    }
//                });
//                itmes.setLabelList(labelList);
//            }
//
//            itmes.setLoginList(loginList);
//        });
//
//        PageResult pageResult = new PageResult();
//        pageResult.setRows(list);
//        pageResult.setTotal(count);
//        return pageResult;
//    }

    @Override
    public PageResult<MememberUser> queryUserGroupPage(MememberUser mememberUser, Page pageQuery) {
        // 根据用户组ID得到该用户组所有第三方会员ID
        TripUserGroupRequest tripUserGroupRequest = new TripUserGroupRequest();
        tripUserGroupRequest.setUserGroupId(mememberUser.getUserGroupId());
        List<String> userGroupIds = tLabelApi.queryMemberIdsByUserGroup(tripUserGroupRequest);
        mememberUser.setUserGroupIds(userGroupIds);

        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MememberUser> list = mememberUserMapper.queryPage(startIndex, pageQuery.getLimit(), mememberUser);
        long count = mememberUserMapper.queryPageCount(mememberUser);

        AdminOperate adminOperate = mememberUser.getAdminOperate();
        MememberLabel mememberLabel = new MememberLabel();

        list.forEach(itmes -> {
            //查询关联表
            mememberLabel.setDeptId(adminOperate.getDeptId());
            mememberLabel.setMemberId(itmes.getId());
            mememberLabel.setDeleteFlag(0);
            List<String> labelList = new ArrayList<>();

            MememberUserRequest mememberRequest = BeanUtil.copy(mememberUser, MememberUserRequest.class);
            List<MememberLabel> result = mememberLabelMapper.query(mememberLabel);
            if (CollectionUtils.isNotEmpty(result)) {
                result.forEach(label -> {
                    if (null != label.getLabelName()) {
                        labelList.add(label.getLabelName());
                    }
                });
                itmes.setLabelList(labelList);
            }
        });

        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public List<String> queryUserHeadInfo(MememberUserRequest form) {
        List<String> deptName = new ArrayList<>();


        return deptName;
    }

    /**
     * 通过标签枚举查询用户
     *
     * @param labelRequest
     * @return
     */
    @Override
    public List<String> queryByLabelType(LabelRequest labelRequest) {
        List<String> stringList = new ArrayList<>();
        //标签类型 1. 性别 2.会员等级 3.会员类型 4.年龄 5.所在地区 6.自定义标签
        switch (labelRequest.getLabelType()) {
            case 1:
                stringList = mememberUserMapper.querySexBatchByEnumsIds(labelRequest);
                break;
            case 2:
                stringList = mememberUserMapper.queryGradeBatchByEnumsIds(labelRequest);
                break;
            case 3:
                stringList = mememberUserMapper.queryTypeBatchByEnumsIds(labelRequest);
                break;
            case 4:
                stringList = mememberUserMapper.queryAgeBatchByEnumsIds(labelRequest);
                break;
            case 5:
                //TODO 所在需求不明确
                break;
            case 6:
                stringList = mememberLabelMapper.queryMemberLabelByEnumsIds(labelRequest);
                break;

        }
        return stringList;
    }


    /**
     * description: 查询会员手机号码
     *
     * @param mememberUser
     * @return
     * @author: jackHe
     * @time: 2020/6/30 16:02
     */
    @Override
    public RestResult<List<MememberUserResponse>> queryUserInfoByPhone(MememberUser mememberUser) {
        if (null == mememberUser.getDeptId() || null == mememberUser.getPhone()) {
            return RestResult.error("9999", "必传参数为空!");
        }
        List<MememberUserResponse> users = mememberUserMapper.queryUserInfoByPhone(mememberUser)
                .stream().map(item -> {
                    MememberUserResponse mememberUserResponse = new MememberUserResponse();
                    BeanUtils.copyProperties(item, mememberUserResponse);
                    return mememberUserResponse;
                }).collect(Collectors.toList());
        return RestResult.success(users);
    }

    /**
     * 为活动中心提供会员列表接口
     *
     * @param request 请求参数
     * @return 响应参数
     * @author tzc
     * @date 2020-7-2 22:07:45
     */
    @Override
    public RestResult<List<MememberUserForMarketResponse>> listMemberUserInfoForMarket(MememberUserForMarketRequest request) {
        log.error("【查询会员列表接口（活动中心专用）】入参 = {}", JSON.toJSONString(request));
        String[] split = null;
        if (null == request) {
            return RestResult.error("1111", "入参为空");
        }
        if (null == request.getParam() || request.getParam().size() < 1) {
            return RestResult.error("2222", "入参中，不同平台的查询参数列表为空");
        }


        List<MememberUserForMarket> param = request.getParam();

        List<MememberUserForMarketResponse> resultList = new ArrayList<>();
        for (MememberUserForMarket item : param) {


            String deptType = item.getDeptType();

            Long[] deptIdArr = item.getDeptIds();
            String[] levelCodeArr = item.getLevelCodes();
            ;
            Long[] memberTypeArr = item.getMemberTypes();
            ;
            Long[] memberGradeIdArr = item.getMemberGradeIds();
            ;

            log.error("【查询会员列表接口（活动中心专用）】入参 deptIdArr = {}", JSON.toJSONString(deptIdArr));
            log.error("【查询会员列表接口（活动中心专用）】入参 levelCodeArr = {}", JSON.toJSONString(levelCodeArr));
            log.error("【查询会员列表接口（活动中心专用）】入参 memberTypeArr = {}", JSON.toJSONString(memberTypeArr));
            log.error("【查询会员列表接口（活动中心专用）】入参 memberGradeIdArr = {}", JSON.toJSONString(memberGradeIdArr));
            log.error("【查询会员列表接口（活动中心专用）】入参 deptType = {}", JSON.toJSONString(deptType));
            List<MememberUser> mememberUsers = mememberUserMapper.listMemberUserInfoForMarket(deptIdArr, levelCodeArr, memberTypeArr, memberGradeIdArr, deptType);
            log.error("【查询会员列表接口（活动中心专用）】出参个数 = {}", mememberUsers == null ? 0 : mememberUsers.size());
            List<MememberUserResponse> collect = mememberUsers.stream().map(m -> {
                MememberUserResponse mememberUserResponse = new MememberUserResponse();
                BeanUtils.copyProperties(m, mememberUserResponse);
                return mememberUserResponse;
            }).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(request.getMemThirdUserIdArr())) {
                List<MememberUserResponse> restList = new ArrayList<>();
                for (String userId : request.getMemThirdUserIdArr()) {
                    List<MememberUserResponse> memList = collect.stream().filter(user -> userId.equals(user.getThirdUserId())).collect(Collectors.toList());
                    restList.addAll(memList);
                }
                collect = restList;
            }
            MememberUserForMarketResponse response = new MememberUserForMarketResponse();
            response.setDeptIds(item.getDeptIds());
            response.setDeptType(deptType);
            response.setMememberUserResponseList(collect);
            resultList.add(response);
        }

        return RestResult.success(resultList);
    }

    @Override
    public RestResult<List<String>> memberUserInfoForMarket(MememberForMarket request) {
        log.info("【查询会员列表接口（活动中心专用）】入参 = {}", JSON.toJSONString(request));
        if (null == request.getMemberGradeIds()) {
            return RestResult.error("9999", "入参会员等级为空");
        }
        if (null == request.getMemberTypes()) {
            return RestResult.error("9999", "入参会员类型为空");
        }
        RestResult result = new RestResult();
        //根据传入的第三方ids 查询会员主表
        final List<String> memThirdUserIdArr = request.getMemThirdUserIdArr();
        MememberUser mememberUser = new MememberUser();
        mememberUser.setUserGroupIds(memThirdUserIdArr);
        final List<MememberUser> memberResult = mememberUserMapper.query(mememberUser);
        if (CollectionUtils.isEmpty(memberResult)) {
            return RestResult.error("9999", "参数错误");
        }
        //查询用户等级表
        List<Long> memUerIds = new ArrayList<>();
        memberResult.forEach(items -> {
            memUerIds.add(items.getId());
        });
        MememberTypeGrade mememberTypeGrade = new MememberTypeGrade();
        mememberTypeGrade.setMemUerIds(memUerIds);
        mememberTypeGrade.setDeleteFlag(0);
        List<MememberTypeGrade> resultMemberType = memberTypeGradeMap.query(mememberTypeGrade);
        List<String> memThirdUserId = new ArrayList<>();
        for (int i = 0; i < resultMemberType.size(); i++) {
            if (booleanRole(request.getMemberGradeIds(), resultMemberType.get(i).getGradeId()) && booleanRole(request.getMemberTypes(), Long.parseLong(resultMemberType.get(i).getMemberType()))) {
                memThirdUserId.add(resultMemberType.get(i).getThirdUserId());
            }
        }

        return RestResult.success(memThirdUserId);
    }

    @Override
    public List<MememberUserResponse> queryMemberByPhone(String phoneList) {
        return mememberUserMapper.queryMemberListByPhone(phoneList);
    }

    @Override
    @Transactional
    public RestResult<String> register(String phone,String inviteCode) {
        MememberUser mememberUser = new MememberUser() {{
            setUserAccount(phone);
            setDeleteFlag(0);
            setPhone(phone);
            setName(phone.substring(phone.length() - 4, phone.length()));
            setCreateTime(new Date());
            setUpdateTime(new Date());
            setIntegral(new BigDecimal(0));
            setStatus(1);
        }};

        mememberUserMapper.insert(mememberUser);

        mememberActionNewService.addMemberIntegralInfoNew(new MemberIntegralRestRequest() {{
            setUserId(mememberUser.getId());
            setChangeTypes(1);
            setObtainMode(ObtainMode.COMMENT_IMG.getCode());
        }});

        mememberGrowthObtainService.obtainOrConsumptionGrowth(new ObtainOrConsumptionGrowthRequest() {{
            setMemberId(mememberUser.getId() + "");
            setObtainMode(ObtainMode.COMMENT_IMG.getCode() + "");
            setActionType(3l);
        }});

        //生成token 返回信息
        String token = UUID.randomUUID().toString();
        redisClientTemplate.setex(RedisKey.H5_LOGIN_TOKEN_.getName() + token, Integer.valueOf(RedisTime.H5_LOGIN_TIME_.getName().toString()), JSONArray.toJSONString(mememberUser));
        return RestResult.success(token);
    }

    @Override
    public RestResult<DistributorShareResponse> queryDistributorShare(DistributorShareRequest request) {
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + request.getToken());
        Map map = JSONArray.parseObject(memStr, Map.class);
        MememberUser mememberUser = mememberUserMapper.queryByPrimaryKey(Long.valueOf(map.get("id").toString()));
        DistributorShareResponse response = new DistributorShareResponse();
        response.setHeadImage(mememberUser.getHeadImage());
        response.setNickName(mememberUser.getNickName());
        response.setId(mememberUser.getId());
        response.setInvitationCode(mememberUser.getInvitationCode());
        return RestResult.success(response);
    }

    @Override
    public PageResult<MememberUser> queryDistributionMemberPage(MememberUser mememberUser, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MememberUser> list = mememberUserMapper.queryPage(startIndex, pageQuery.getLimit(), mememberUser);
        long count = mememberUserMapper.queryPageCount(mememberUser);
        list.forEach(items -> {
            DisCommissionInfo disCommissionInfo = new DisCommissionInfo();
            disCommissionInfo.setMemberId(items.getId());
            BigDecimal commissionCount = disCommissionInfoService.getCommissionCount(disCommissionInfo);
            items.setDistributionTotal(commissionCount);
            DisCashLog disCashLog = new DisCashLog();
            disCashLog.setStatus(8);
            disCashLog.setMemberId(items.getId());
            //已提现
            BigDecimal withdrawalCount = disCashLogService.getWithdrawalCount(disCashLog);
            items.setWithdrawn(withdrawalCount);
            disCashLog.setStatus(2);
            BigDecimal withdrawalCount1 = disCashLogService.getWithdrawalCount(disCashLog);
            items.setWithdrawn(withdrawalCount1);
            disCashLog.setStatus(null);
            BigDecimal withdrawalCount2 = disCashLogService.getWithdrawalCount(disCashLog);
            if (null != withdrawalCount2 && null != withdrawalCount) {
                items.setWithdrawable(withdrawalCount2.subtract(withdrawalCount));
            }
        });
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }


    public static boolean booleanRole(Long[] arr, Long targetValue) {
        for (Long s : arr) {
            if (s.equals(targetValue)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public PageResult<MememberUser> listRestPage(MememberUser mememberUser, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();

        List<MememberUser> list = mememberUserMapper.listRestPage(startIndex, pageQuery.getLimit(), mememberUser);
        long count = mememberUserMapper.listRestPageCount(mememberUser);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 添加上级下级
     *
     * @param request
     * @return
     */
    @Override
    public RestResult<Boolean> addHigherOrLower(DistributionRestRequest request) {
        //查询当前登录人
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + request.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }
        if (request.getInvitationType() == null) {
            return RestResult.error("9999", "邀请类型不能为空");
        }

        List<MememberUser> mememberUserList = mememberUserMapper.query(new MememberUser() {{
            setInvitationCode(request.getInvitationCode());
            setDeleteFlag(0);
        }});
        if (CollectionUtils.isEmpty(mememberUserList)) {
            return RestResult.error("9999", "邀请码不存在");
        }
        if(request.getInvitationCode()==null){
            return RestResult.error("9999", "邀请码不能为空");
        }
        if (request.getInvitationType() == 1) {
            member.setAllocationPid(mememberUserList.get(0).getId());
            member.setUpdateTime(new Date());
            mememberUserMapper.update(member);
        } else {
           /* mememberUserList.get(0).setAllocationPid(member.getId());
            mememberUserList.get(0).setUpdateTime(new Date());
            mememberUserMapper.update(mememberUserList.get(0));*/
            mememberUserList.get(0).setAllocationPid(member.getId());
            mememberUserList.get(0).setUpdateTime(new Date());
            mememberUserMapper.update(mememberUserList.get(0));
        }
        return RestResult.success(true);
    }

    @Override
    public List<MememberUserResponse> queryByThirdUserIds(String userIds) {
        return null;
    }

    @Override
    public List<MememberUserResponse> listPage(MememberUserRequest user) {
        user.setStart((user.getStatus()-1)*user.getLimit());
        List<MememberUser> mememberUsers = mememberUserMapper.listPage(user);
        List<MememberUserResponse> responses = new ArrayList<>();
        if (mememberUsers!=null&&mememberUsers.size()>0){
            for (MememberUser mememberUser : mememberUsers) {
                MememberUserResponse response = new MememberUserResponse();
                BeanUtils.copyProperties(mememberUser,response);
                responses.add(response);
            }
        }
        return responses;
    }

    @Override
    public Long updateMember(MememberUserRequest request) {
        Long result = mememberUserMapper.updateMember(request);
        return null;
    }

    @Override
    public RestResult<Map<String, Long>> queryRegisteredCount(MememberUserRequest request) {
        Map<String, Long> result = Maps.newHashMap();
        List<Map<String, Object>> list = mememberUserMapper.queryRegisteredCount(request);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(map -> {
                String channelCode = (String) map.get("channelCode");
                Long count = (Long) map.get("count");
                result.put(StringUtils.isEmpty(channelCode) ? "others" : channelCode, null == count ? 0 : count);
            });
        }
        return RestResult.success(result);
    }

    @Override
    public RestResult<List<MememberUserResponse>> queryRegistered(MememberUserRequest request) {
        List<MememberUser> users = mememberUserMapper.queryRegistered(request);
        List<MememberUserResponse> result = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(users)) {
            users.forEach(user -> {
                MememberUserResponse target = new MememberUserResponse();
                BeanUtils.copyProperties(user, target);
                result.add(target);
            });
        }
        return RestResult.success(result);
    }

    /**
     * 聚合用户信息及微常准用户信息
     * @param request
     * @return
     */
    @Override
    public RestResult<MemberInfoResponse> aggregationUserInfo(MememberInfoRequest request) {

        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + request.getToken());
        log.info("aggregationUserInfo 入参：token获取",memStr);
        if (org.apache.commons.lang.StringUtils.isEmpty(memStr)) {
            return RestResult.error("4000", "登录失效");
        }
        Map map = JSONArray.parseObject(memStr, Map.class);
        MememberUser userInfo = mememberUserMapper.queryByPrimaryKey(Long.valueOf(map.get("id").toString()));
        if(userInfo==null){
            return RestResult.error("9999","用户不存在");
        }
        MemberInfoResponse memberInfo = BeanUtil.copy(userInfo, MemberInfoResponse.class);
        memberInfo.setUserId(userInfo.getId().toString());
        RestResult<JSONObject> restResult = toScoreOrderApi.queryUser(new ScoreOrderRequest(){{
//            setUserId(mememberUser.getId().toString());
            setUserId("1234");
        }});
        JSONObject jsonObject = restResult.getCode().equals("0000")?restResult.getData():null;
        memberInfo.setBalance(jsonObject==null ? BigDecimal.ZERO:jsonObject.getBigDecimal("balance"));
        return RestResult.success(memberInfo);
    }

    @Override
    public Boolean updateStatus(MememberUserRequest form) {
        Integer i = mememberUserMapper.updateStatus(form);
        return i>0;
    }

    @Override
    public List<MememberUserResponse> count() {
        List<MememberUser> list= mememberUserMapper.count();
        List<MememberUserResponse> collect = list.stream().map(item -> {
            MememberUserResponse response = new MememberUserResponse();
            response.setStatus(item.getStatus());
            response.setIsBlacklist(item.getIsBlacklist());
            return response;
        }).collect(Collectors.toList());
        return collect;
    }


    /**
     *
     *
     * @description: 修改用户白名单
     * @return:
     * @author: fengrui
     * @time: 2020/12/08 23:13
     */
    @Scheduled(cron = "0 0 22 * * ?")
    public void updateMeber(){
        log.error("修改会员白名单状态开始");
        Integer integer = mememberUserMapper.updateMemberStatus(new Date());
        log.error("是否将白名单修改状态修改成功{}",integer!=null);
    }

    /**
     *
     *
     * @description: 修改用户灰名单
     * @return:
     * @author: fengrui
     * @time: 2020/12/08 23:13
     */
//    @Scheduled(cron = "0 0 22 * * ? *")
    @Scheduled(cron = "0 0 22 * * ?")
    public void updateMebers(){
        log.info("修改会员白名单状态开始");
        List<String> list = sysUserApi.userPhone();
        System.out.println("fff");
        Integer integer = null;
        if (list!=null&& list.size()>0){
            integer = mememberUserMapper.updateMemberGray(list);
        }
        log.info("是否将白名单修改状态修改成功{}",integer!=null);
    }
}
